package models

import (
	"fmt"
	"xcloud-oauth2-server/util/migrations"

	"gorm.io/gorm"
)

var (
	list = []migrations.MigrationStage{
		{
			Name:     "initial",
			Function: migrate0001,
		},
	}
)

// MigrateAll executes all migrations
func MigrateAll(db *gorm.DB) error {
	return migrations.Migrate(db, list)
}

func migrate0001(db *gorm.DB, name string) error {
	//-------------
	// OAUTH models
	//-------------

	err := db.AutoMigrate(&OauthClient{})
	if err != nil {
		return fmt.Errorf("Error creating oauth_clients table: %s", err)
	}
	if err = db.AutoMigrate(&OauthScope{}); err != nil {
		return fmt.Errorf("Error creating oauth_scopes table: %s", err)
	}
	if err = db.AutoMigrate(&OauthRole{}); err != nil {
		return fmt.Errorf("Error creating oauth_roles table: %s", err)
	}
	if err = db.AutoMigrate(&OauthUser{}); err != nil {
		return fmt.Errorf("Error creating oauth_users table: %s", err)
	}

	err = db.AutoMigrate(&OauthRefreshToken{})
	if err != nil {
		return fmt.Errorf("Error creating oauth_refresh_tokens table: %s", err)
	}

	//err = db.Migrator().CreateTable(&OauthRefreshToken{})
	//if err != nil {
	//	return fmt.Errorf("Error creating oauth_refresh_tokens table: %s", err)
	//}

	fmt.Println("---------- table OauthAccessToken migrate start -------")
	if err = db.AutoMigrate(&OauthAccessToken{}); err != nil {
		return fmt.Errorf("Error creating oauth_access_tokens table: %s", err)
	}
	fmt.Println("---------- table OauthAccessToken migrate end -------")

	if err = db.AutoMigrate(&OauthAuthorizationCode{}); err != nil {
		return fmt.Errorf("Error creating oauth_authorization_codes table: %s", err)
	}

	return nil

}
